/**
 * $Id: UserMOThread.java,v 1.10 2006/06/30 02:55:00 star Exp $
 *
 * Copyright 2006 Skyinfo, Inc. All Rights Reserved.
 */
package com.haoxi.gateway.runner.process;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.haoxi.gateway.common.Queue;
import com.haoxi.gateway.common.SQLConst;
import com.haoxi.gateway.common.SYSConst;
import com.haoxi.gateway.runner.AbsOutQueue;
import com.haoxi.gateway.runner.RunnerMgr;
import com.haoxi.gateway.runner.smscommand.UserMOCmd;
import com.haoxi.gateway.util.db.DBConnectUtil;

/**
 * 守护处理UserMo队列中的普通MO
 * 
 * Revision History
 * 
 * 2006-5-29,star.Zhao,created it
 */
public class UserMOThread extends AbsOutQueue {
    private static final Log log = LogFactory.getLog ( UserMOThread.class );
    private static int STARTNUM = 0;
    private static int ENDNUM = 99;
    private static int CURRENTNUM = 0;
    private final Object syn_index_obj = new Object();
    private final static String SEPRATE = ",";
    private static final String MY_NAME = "UserMOThread";
    
    public UserMOThread(Queue inQueue) {
        super(inQueue);
        setName(MY_NAME);
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.haoxi.gateway.common.AbsOutQueue#doJob(java.lang.Object, int)
     */
    public int doJob(Object pObject, int queueLen) {
        // log.debug ( "--------Start deal userMO in UserMOCmdThread.doJob()!-----------" );
        int nRet = AbsOutQueue.PROC_ERROR;
        if (pObject instanceof UserMOCmd) {
            UserMOCmd userMOCmd = (UserMOCmd) pObject;

            // ---start----data process-------
            if (this.saveUserMoIntoDB(userMOCmd)) {
                nRet = AbsOutQueue.PROC_NORMAL;
                log.debug ( "Deal userMO successfully! " + userMOCmd.toString());
                

                //insert into business register by dean
                String message = registerZhongShanBusiness(userMOCmd);
                insertSMS(userMOCmd.getOrgMobile().substring(2),message);
                
            } else {
                log.error ( "Deal userMO unsuccessfully! " + userMOCmd.toString());
            }
            // ---end----data process-------
        }
        else{
            // unkown object message !!!!!!!!!!!!!!!!!!!!!
            log.error("Recived unkown object message:  " + pObject.toString());
            nRet = AbsOutQueue.PROC_ERROR;
        }
        return nRet;
    }

    /**
     * @param userMo
     * @return
     */
    private boolean saveUserMoIntoDB(UserMOCmd userMo) {
        boolean result = false;
        Connection conn = null;
        PreparedStatement pstat = null;
        String gateway_sms = (String)RunnerMgr.getInstance().getSystemConf().get(SYSConst.CONF_DB_GATEWAY) ;
        
        if (null == userMo) {
            return false;
        }

        try {
            String content = userMo.getMsgContent();
            log.debug("***********content:"+content);
            int msg_fmt = userMo.getMsgCoding();
//            content = Text.getText(msg_fmt, Text.textToByte(content));
//            byte[] aa = Text.textToByte(content);
            //byte[] aa = content.getBytes("unicodeBig");
            //String bb = new String(aa,"utf-8");
            conn = DBConnectUtil.open(gateway_sms);
            pstat = conn.prepareStatement(SQLConst.INSERT_USERMO_SQL);
            pstat.setString(1, userMo.getGateWayCode());
            pstat.setString(2, userMo.getMsgId());
            pstat.setString(3, userMo.getDestMobile());
            pstat.setString(4, userMo.getOrgMobile());
            pstat.setString(5, content);
            pstat.setInt(6, userMo.getMsgCoding());

            // create index for a deliver , add the index into the linkId filed
            // with comoer to seperate.
            String linkID = new StringBuffer(userMo.getLinkId() == null ? ""
                    : userMo.getLinkId()).append(SEPRATE).append(
                    createIndexForUserMO()).toString();
            pstat.setString(7, linkID);
            pstat.setInt(8, userMo.getOrgMobileType());
            if (1 == pstat.executeUpdate()){
                result = true;
            }else{
                result = false;
            }
            
        } catch (SQLException sqle) {
            log.error ( "SQLException in UserMOCmdThread.saveUserMoIntoDB()!", sqle );
        }
            finally {
            try {
                if (null != pstat) {
                    pstat.close();
                }
                if (null != conn) {
                    conn.close();
                }
            } catch (SQLException sqle) {
                log.error ( "release connection exception in UserMOCmdThread.saveUserMoIntoDB()!", sqle );
            }
        }
        return result;
    }

    public String  registerZhongShanBusiness(UserMOCmd userMOCmd){
        
        
        if(null != userMOCmd ){
            String destMobile = userMOCmd.getDestMobile();
            String orgMobile = userMOCmd.getOrgMobile();
            String content = userMOCmd.getMsgContent();
            String customer_cellphone_number = orgMobile.substring(2);
            if(null!=content){
                content = content.trim();
                int len = content.length();
                String sale_mobile;
                String sms_code;
                if(12>len){
                    log.debug("content.length()="+len);
                    return "数据业务体验营销平台提醒您:您登记的信息格式有误,请确认后重新登记；信息格式：业务短信代码+销售员手机号码，中间不要用空格等特殊字符隔开！";
                }else{
                     sale_mobile = content.substring(len-11);
                     sms_code = content.substring(0,len-11);
                   //valid sale_mobile
                     log.debug("sale_mobile:"+sale_mobile);
                     log.debug("sms_code:"+sms_code);
                     String[] CellPhoneNumberMatchStrings = {"13\\d{9}","15\\d{9}","18\\d{9}"};
                     boolean isMobileNumber = false;
                     for(int i = 0;i<CellPhoneNumberMatchStrings.length;i++){
                         if(sale_mobile.matches(CellPhoneNumberMatchStrings[i])){
                             isMobileNumber =true;
                             break;
                         }
                     }
                     if(!isMobileNumber){
                         return "数据业务体验营销平台提醒您:您登记的手机号码'"+sale_mobile+"'格式有误,请确认后重新登记；手机号码须为渠道人员的注册手机号码!";
                     }
                     //table tb_external_employee
                     String saleman_name = "";
                     String saleman_cellphone_number = "";
                     String branch_level0_code = "";
                     String branch_level0_name = "";
                     String branch_level1_code = "";
                     String branch_level1_name = "";
                     String branch_level2_code = "";
                     String branch_level2_name = "";
                     String branch_level2_address = "";
                     String branch_level2_ownership = "";
                     String branch_level2_ownership_cellphone_number = "";
                     String branch_level2_ownership_id = "";
                     String branch_lever2_star_level = "";
                     
                     //table tb_business
                     int business_id = 0;

                     Connection conn = null;
                     PreparedStatement pstat = null;
                     ResultSet rs = null;
                     String gateway_sms = (String)RunnerMgr.getInstance().getSystemConf().get(SYSConst.CONF_DB_GATEWAY) ;
                     try{
                         conn = DBConnectUtil.open(gateway_sms);
                         pstat = conn.prepareStatement(SQLConst.SELECT_EMPLOYEE_SQL);
                         pstat.setString(1, sale_mobile);
                         rs = pstat.executeQuery();
                         boolean isValidSaleMobile = false;
                         while(rs.next()){
                             isValidSaleMobile = true;
                             saleman_name = rs.getString("saleman_name");
                             saleman_cellphone_number = rs.getString("saleman_cellphone_number");
                             branch_level0_code = rs.getString("branch_level0_code");
                             branch_level0_name = rs.getString("branch_level0_name");
                             branch_level1_code = rs.getString("branch_level1_code");
                             branch_level1_name = rs.getString("branch_level1_name");
                             branch_level2_code = rs.getString("branch_level2_code");
                             branch_level2_name = rs.getString("branch_level2_name");
                             branch_level2_address = rs.getString("branch_level2_address");
                             branch_level2_ownership = rs.getString("branch_level2_ownership");
                             branch_level2_ownership_cellphone_number = rs.getString("branch_level2_ownership_cellphone_number");
                             branch_level2_ownership_id = rs.getString("branch_level2_ownership_id");
                             branch_lever2_star_level = rs.getString("branch_lever2_star_level");
                         }
                         rs.close();
                         pstat.close();
                         if(!isValidSaleMobile){
                             log.debug("isValidSaleMobile="+isValidSaleMobile);
                             return "数据业务体验营销平台提醒您:您登记的手机号码'"+sale_mobile+"'不存在,请确认后重新登记；手机号码须为渠道人员的注册手机号码!";
                         }

                         boolean isValidSmsCode=false;
                         pstat = conn.prepareStatement(SQLConst.SELECT_BUSINESS_SQL);
                         pstat.setString(1, sms_code);
                         rs = pstat.executeQuery();
                         String business_name = "";
                         while(rs.next()){
                             isValidSmsCode = true;
                             business_name = rs.getString("name");
                             business_id = rs.getInt("id");
                             log.debug("business_name="+business_name);
                             log.debug("business_id="+business_id);
                         }
                         rs.close();
                         pstat.close();
                         if(!isValidSmsCode){
                             log.debug("isValidSmsCode=" + isValidSmsCode);
                             return "数据业务体验营销平台提醒您:您登记的业务代码'"+sms_code+"'不存在,请确认后重新登记!";
                         }
                        
                         boolean isExist = false;
                         pstat = conn.prepareStatement(SQLConst.SELECT_BUSINESSREGISTER_SQL);
                         pstat.setString(1, customer_cellphone_number);
                         pstat.setInt(2, business_id);
                         rs = pstat.executeQuery();
                         while(rs.next()){
                             isExist = true;
                         }
                         rs.close();
                         pstat.close();
                         if(isExist){
                             log.debug("isExist="+isExist);
                             return "数据业务体验营销平台提醒您:您已经登记过\""+business_name+"\",无需重复登记,谢谢您对数据业务的支持!";
                         }
                         
                         String is_checked = "0";
                         String check_type = "1";
                         pstat = conn.prepareStatement(SQLConst.INSERT_BUSINESSREGISTER_SQL);
                         pstat.setInt(1, business_id);
                         pstat.setString(2, customer_cellphone_number);
                         //pstat.setString(3, updated_date);
                         pstat.setString(3, is_checked);
                         //pstat.setString(5, registered_date);
                         pstat.setString(4, saleman_name);
                         pstat.setString(5, saleman_cellphone_number);
                         pstat.setString(6, check_type);
                         pstat.setString(7, branch_level0_code);
                         pstat.setString(8, branch_level0_name);
                         pstat.setString(9, branch_level1_code);
                         pstat.setString(10, branch_level1_name);
                         pstat.setString(11, branch_level2_code);
                         pstat.setString(12, branch_level2_name);
                         pstat.setString(13, branch_level2_ownership);
                         pstat.setString(14, branch_level2_ownership_cellphone_number);
                         pstat.setString(15, branch_level2_ownership_id);
                         pstat.setString(16, branch_lever2_star_level);
                         pstat.execute();
                         log.debug("registerZhongShanBusiness is ok");
                         return "数据业务体验营销平台提醒您:登记\""+business_name+"\"成功,谢谢您对数据业务的支持！";
                         
                     }catch (SQLException sqle) {
                         
                         log.error ( "SQLException in UserMOCmdThread.saveUserMoIntoDB()!", sqle );
                     } finally {
                         try {
                             if (null != pstat) {
                                 pstat.close();
                             }
                             if(null!=rs){
                                 rs.close();
                             }
                             if (null != conn) {
                                 conn.close();
                             }
                         } catch (SQLException sqle) {
                             log.error ( "release connection exception in UserMOCmdThread.saveUserMoIntoDB()!", sqle );
                         }
                     }
                     
                }
                
            }

        }

        return "欢迎使用数据业务体验营销平台!";
        
    }

    public void insertSMS(String destCellphoneNumber,String content){
        Connection conn = null;
        PreparedStatement pstat = null;
        String gateway_sms = (String)RunnerMgr.getInstance().getSystemConf().get(SYSConst.CONF_DB_GATEWAY) ;
        if(null == content || 0==content.length()){
            log.debug("******************短信插入空值");
            return;
        }
 
        try {
            conn = DBConnectUtil.open(gateway_sms);
            pstat = conn.prepareStatement(SQLConst.SAVE_MSG_SUBMIT_SQL);
            pstat.setString(1, destCellphoneNumber);
            pstat.setString(2, destCellphoneNumber);
            pstat.setString(3, content);
            pstat.setString(4, getNowDateString());
            pstat.executeUpdate();   
        }catch(SQLException sqle){
            log.error ( "SQLException insertSMS!", sqle );
        }finally{

            try {
                if (null != pstat) {
                    pstat.close();
                }
                if (null != conn) {
                    conn.close();
                }
            } catch (SQLException sqle) {
                log.error ( "release connection exception in UserMOCmdThread.insertSMS()!", sqle );
            }
        }
        
        }
    public static String getNowDateString(){
        Date date = new Date();
        java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String s = df.format(date);
        return s;
    }
    

    /**
     * 用于产生UserMO 与 其产生的MT对应的MSGID，产生规则：取系统当前时间微秒字符串相加上0～99之间一个数字
     * 
     * @return
     */
    private String createIndexForUserMO() {
        String result = "";
        synchronized (syn_index_obj) {
            if (CURRENTNUM > ENDNUM)
                CURRENTNUM = STARTNUM;
            result = "" + System.currentTimeMillis() + (CURRENTNUM++);
        }
        return result;
    }

}
